import axios from 'axios'
import state_a from "../store";
import config from "../../static/config.js";

axios.defaults.withCredentials = true

// const bUrl = 'http://2049g328c3.iask.in:22192';
const bUrl = config.url;

export const wsapi = () => {
  return new WebSocket(wsUrl)
};
export const get = (url, params) => {
  return axios.get(url, {
    baseURL: bUrl,
    params: params,
    headers: {
      'token': localStorage.getItem('token')
    }
  }).then(res => res.data);
}

export const post = (url, params) => {
  return axios.post(url, params, {
    baseURL: bUrl,
    headers: {
      'token': localStorage.getItem('token')
    }
  }).then(res => res.data);
}

export const pat = (url, params) => {
  return axios.patch(url, params, {
    baseURL: bUrl,
    headers: {
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  }).then(res => res.data);
}

export const del = (url, params) => {
  return axios.delete(url, {
    baseURL: bUrl,
    params: params,
    headers: {
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  }).then(res => res.data);
}

export const common = self => error => success => data => {
  if (data.code == -1) { //token到期
    self();
  } else if (data.code == 0) { //处理错误响应
    error();
  } else if (data.code == 1) { //处理成功响应
    success();
  }
}

export const getRefresh = (...func) => {
  function runFunc(func) {
    if (func.length == 1) {
      if (typeof func[0] == 'function') func[0]();
    } else {
      if (typeof func[0] == 'function') {
        let rest = [];
        for (var i = 1; i < func.length; i++) {
          rest.push(func[i])
        }
        func[0](...rest);
      }
    }
  };
  //该行针对有autologin执行时的情况，马上把原方法再运行一次
  if (state_a.getters.getRole == null)
    runFunc(func);
  else {
    return new Promise( (resolve, reject) => {
      // console.log('refresh begin2');
      get('/auth/refresh').then(data => {
        if (data.code != 0) {
          localStorage.removeItem('token');
          alert("请刷新页面!");
        } else {
          // console.log('refresh success');
          localStorage.setItem('token', data.data.token);
          runFunc(func);
        }
        resolve(1);
      });
    })
  }
}

export const execution = (funcs) => {

}
